<template>
  <el-card class="box-card">
    <el-button type="primary" size="default" icon="Plus" @click="handleAdd">
      添加品牌
    </el-button>

    <el-table
      :data="tableData"
      stripe
      border
      style="width: 100%; margin: 10px 0"
    >
      <el-table-column
        width="110"
        align="center"
        prop="date"
        label="序号"
        type="index"
      />
      <el-table-column width="110" prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO" align="center">
        <template #default="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column width="200" prop="address" label="操作">
        <template #default="{ row }">
          <el-button type="primary" @click="handleEdit(row)">修改</el-button>
          <el-popconfirm
            :title="`您确认要删除${row.tmName}吗？`"
            width="250"
            @confirm="removeTradeMark(row.id)"
          >
            <template #reference>
              <el-button type="danger" @click="handleDelete(row.id)">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, , prev, pager, next, jumper, ->,sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
  <!-- 对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="tradeForm.id ? '修改品牌' : '新增品牌'"
  >
    <el-form :model="tradeForm" style="width: 80%" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          v-model="tradeForm.tmName"
          autocomplete="off"
          placeholder="请输入品牌名称"
        />
      </el-form-item>
      <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
        <el-upload
          v-model="tradeForm.logoUrl"
          class="avatar-uploader"
          action="http://114.115.179.162:8022/prod-api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="tradeForm.logoUrl"
            :src="tradeForm.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqHasTradeMark,
  reqSaveTradeMark,
  reqUpdateTradeMark,
  reqRemoveTradeMark,
} from '@/api/product/trademark'
import { Trademark } from '@/api/product/trademark/type'
import { ElMessage } from 'element-plus'
const pageNo = ref<number>(1)
const limit = ref<number>(3)
const total = ref<number>(0)
const dialogFormVisible = ref<boolean>(false)
const tradeForm = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})
const tableData = ref([{}])
let formRef = ref()

const validatorTmName = (rule: any, value: any, callback: any) => {
  console.log(`output->value`, value)
  if (value.length < 2 || value.length > 10) {
    callback(new Error('品牌名称长度为2-10位'))
  } else {
    callback()
  }
}

const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, message: '请选择品牌图片', trigger: 'change' }],
}

const getHasTradeMark = async (pager = 1) => {
  pageNo.value = pager
  let result = await reqHasTradeMark(pageNo.value, limit.value)
  if (result.code === 200) {
    // console.log('获取品牌列表成功', result.data)
    total.value = result.data.total
    tableData.value = result.data.records
  } else {
    // console.log('获取品牌列表失败')
  }
}

onMounted(() => {
  getHasTradeMark()
})

const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleAdd = () => {
  formRef.value?.clearValidate('logoUrl')
  formRef.value?.clearValidate('tmName')
  dialogFormVisible.value = true
  tradeForm.tmName = ''
  tradeForm.logoUrl = ''
  tradeForm.id = 0
}
const handleSizeChange = () => {
  getHasTradeMark()
}
const handleCurrentChange = (val: number) => {
  getHasTradeMark(val)
}
const handleEdit = (row: Trademark) => {
  formRef.value?.clearValidate('logoUrl')
  formRef.value?.clearValidate('tmName')
  dialogFormVisible.value = true
  tradeForm.tmName = row.tmName
  tradeForm.logoUrl = row.logoUrl
  tradeForm.id = row.id
}
const handleDelete = (id: any) => {
  // console.log('删除品牌', id)
}

const handleAvatarSuccess = (res: any, file: any) => {
  if (res.code === 200) {
    ElMessage.success('上传成功')
    tradeForm.logoUrl = res.data
    // imageUrl.value = URL.createObjectURL(file.raw)
    formRef.value?.clearValidate('logoUrl')
  } else {
    ElMessage.error('上传失败')
  }
}

const beforeAvatarUpload = (file: any) => {
  // console.log(`output->file.type`,file.type)
  const isLt2M = file.size / 1024 / 1024 < 4
  if (
    file.type == 'image/jpeg' ||
    file.type == 'image/png' ||
    file.type == 'image/gif'
  ) {
  } else {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Avatar picture size can not exceed 4MB!')
    return false
  }
}
const cancel = () => {
  dialogFormVisible.value = false
}
const confirm = async () => {
  // 在发请求之前，要求对整个表单进行校验
  await formRef.value?.validate()
  let result
  if (tradeForm.id) {
    result = await reqUpdateTradeMark(tradeForm)
  } else {
    result = await reqSaveTradeMark(tradeForm)
  }
  if (result.code === 200) {
    ElMessage.success(`${tradeForm.id ? '修改' : '添加'}成功`)
    getHasTradeMark(tradeForm.id ? pageNo.value : 1)
  } else {
    ElMessage.error(`${tradeForm.id ? '修改' : '添加'}成功`)
  }
  dialogFormVisible.value = false
}

const removeTradeMark = async (id: number) => {
  // console.log(`output->id`,id)
  let result = await reqRemoveTradeMark(id)
  if (result.code === 200) {
    ElMessage.success('删除成功')
    getHasTradeMark(pageNo.value)
  } else {
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
